import { useState } from "react";
/**
 * 1. 定位组件中不同的视图状态 
 * 2. 确定是什么触发了这些状态的改变
 *  2.1 人为输入
 *  2.2 计算机输入
 */

export default function Form() {
  const [answer, setAnswer] = useState('');
  const [error, setError] = useState(null);
  const [status, setStatus] = useState('typing'); // 'typing', 'submitting', or 'success'

  const handleTextareaChange = (e) => {
    setAnswer(e.target.value);
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('submitting');
    try {
      await submitForm();
      setStatus('success');
    } catch (err) {
      setStatus('error');
      setError(err)
    }
  }

  if (status === 'success') {
    return <h1>That's right!</h1>
  }

  function submitForm() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        let shouldError = answer.toLowerCase() !== 'lima';
        if (shouldError) {
          reject(new Error('Good guess but a wrong answer. Try again!'));
        } else {
          resolve();
        }
      }, 1500)
    })
  }

  return (
    <>
      <h2>City quiz</h2>
      <p>In which city is there a billboard that turns air into drinkable water?</p>
      <form onSubmit={handleSubmit}>
        <textarea
          value={answer}
          onChange={handleTextareaChange}
          disabled={
            status === 'submitting'
          } />
        <br />
        <button disabled={
          answer.length === 0 ||
          status === 'submitting'
        }
        >
          Submit
        </button>
        {status === 'error' &&
          <p className="Error">
            Good guess but a wrong answer. Try again!
          </p>
        }
      </form>
    </>
  )
}